package com.wisdytech.linkdcs.measuretool.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.constants.DictKeyConstants;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.measuretool.dao.MeasureRecordDao;
import com.wisdytech.linkdcs.measuretool.dao.MeasureRecordDetailDao;
import com.wisdytech.linkdcs.measuretool.dao.MeasureToolDao;
import com.wisdytech.linkdcs.measuretool.model.MeasureRecord;
import com.wisdytech.linkdcs.measuretool.model.MeasureRecordDetail;
import com.wisdytech.linkdcs.measuretool.model.MeasureTool;
import com.wisdytech.linkdcs.measuretool.service.IMeasureRecordService;
import com.wisdytech.linkdcs.measuretool.vo.MeasureToolCheckVO;
import com.wisdytech.linkdcs.system.model.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhanghailin
 * @since 2018-06-19
 */
@Service
@Transactional
public class MeasureRecordServiceImpl extends BaseService<MeasureRecordDao, MeasureRecord> implements IMeasureRecordService {

    @Resource
    private MeasureRecordDao measureRecordDao;

    @Resource
    private MeasureRecordDetailDao measureRecordDetailDao;

    @Resource
    private MeasureToolDao measureToolDao;

    @Override
    public Boolean measureToolCheck(MeasureToolCheckVO vo, SysUser operator) {
        Integer operatorCount = 0;
        if (operator == null)
            throw new ServiceException("操作人不能为空");
        if (vo == null || StringUtils.isBlank(vo.getMeasureToolCode()))
            throw new ServiceException("参数错误");

        //保存校验记录
        MeasureRecord record = new MeasureRecord();
        String pkId = BaseUtil.getUUID();
        record.setPkId(pkId);
        record.setPkId(pkId);
        record.setDelFlag(CommonConstants.DEL_FLAG);
        record.setCreateDate(new Date());
        record.setCreateUser(operator.getUsername());
        record.setCheckUser(vo.getCheckUser());
        record.setCheckDate(vo.getCheckDate());
        record.setConfirmUser(vo.getConfirmUser());
        record.setConfirmDate(vo.getConfirmDate());
        record.setRemark(vo.getRemark());
        record.setMeasureToolCode(vo.getMeasureToolCode());
        record.setDetectionSite(vo.getDetectionSite());
        record.setHumidity(vo.getHumidity());
        record.setTemperature(vo.getTemperature());
        record.setStandardCert(vo.getStandardCert());
        record.setStandardCode(vo.getStandardCode());
        record.setStandardName(vo.getStandardName());
        record.setEquipCode(vo.getEquipCode());
        operatorCount = measureRecordDao.insert(record);
        //保存校验结果明细
        List<MeasureRecordDetail> list = vo.getDetails();
        for (MeasureRecordDetail detail : list) {
            detail.setPkId(BaseUtil.getUUID());
            detail.setCreateUser(operator.getUsername());
            detail.setCreateDate(new Date());
            detail.setDelFlag(CommonConstants.DEL_FLAG);
            detail.setRecordId(pkId);
            //TODO 循环操作数据库 应该改成 一次批量插入 但是mysql和oracle批量插入数据的语法不同，为兼容暂且如果
            measureRecordDetailDao.insert(detail);
        }

        MeasureTool tool = new MeasureTool();
        MeasureTool params = new MeasureTool();
        params.setMeasureToolCode(vo.getMeasureToolCode());
        params.setDelFlag(CommonConstants.DEL_FLAG);
        //查询校验周期
        MeasureTool t = measureToolDao.selectOne(params);
        //上次校验日期为这次校验日期
        tool.setLastCheckDate(vo.getCheckDate());
        //下次校验日期为这次校验日期加校验周期
        tool.setNextCheckDate(getAfterDate(t.getCheckCycle().intValue(), vo.getCheckDate()));

        //hack 方法 因为在MeasureTool中设置了mp的FieldStrategy 为ignore用来更新空值，所以此处如果不加的话，值会被更新掉，慎用
        tool.setCheckCycle(t.getCheckCycle());
        EntityWrapper<MeasureTool> ew = new EntityWrapper<>();
        ew.eq("measure_tool_code", vo.getMeasureToolCode())
                .eq("del_flag", CommonConstants.DEL_FLAG);
        measureToolDao.update(tool, ew);
        return operatorCount > 0;
    }

    @Override
    public PageInfo<MeasureToolCheckVO> getMeasureToolCheckRecordList(String measureToolCode, String measureToolName, String checkType, String supplier, String equipCode, String equipName, String checkDateStart, String checkDateEnd, Filter filter) {
        Map<String, Object> params = new HashMap<>();
        params.put("checkTypeParentKey", DictKeyConstants.MEASURE_TOOL_CHECK_TYPE_PARENT_KEY);
        if (StringUtils.isNotBlank(measureToolCode)) {
            params.put("measureToolCode", measureToolCode);
        }
        if (StringUtils.isNotBlank(measureToolName)) {
            params.put("measureToolName", measureToolName);
        }
        if (StringUtils.isNotBlank(supplier)) {
            params.put("supplier", supplier);
        }
        if (StringUtils.isNotBlank(checkType)) {
            params.put("checkType", checkType);
        }
        if (StringUtils.isNotBlank(equipCode)) {
            params.put("equipCode", equipCode);
        }
        if (StringUtils.isNotBlank(equipName)) {
            params.put("equipName", equipName);
        }
        if (StringUtils.isNotBlank(checkDateStart)) {
            params.put("checkDateStart", checkDateStart);
        }
        if (StringUtils.isNotBlank(checkDateEnd)) {
            params.put("checkDateEnd", checkDateEnd);
        }

        List<MeasureToolCheckVO> list = this.beforeList(MeasureRecordDao.class,filter).getMeasureToolCheckRecordList(params);
        return new PageInfo<>(list);
    }

    @Override
    public MeasureToolCheckVO getMeasureToolCheckResult(String pkId) {
        if (StringUtils.isBlank(pkId)) {
            return null;
        }
        MeasureToolCheckVO vo = this.measureRecordDao.getMeasureToolCheckResult(pkId);
        if(vo == null) {
            throw new ServiceException("无此校验记录");
        }
        EntityWrapper<MeasureRecordDetail> ew = new EntityWrapper<>();
        ew.eq("del_flag",CommonConstants.DEL_FLAG)
                .eq("record_id",pkId);
        //查询校验明细
        List<MeasureRecordDetail> list = measureRecordDetailDao.selectList(ew);
        vo.setDetails(list);
        return vo;
    }

    /**
     * 获取过去第几天的日期
     *
     * @param past 天数
     * @return Date
     */
    private Date getAfterDate(int past, Date date) {
        Calendar calendar = Calendar.getInstance();
        if (date != null) calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
        return calendar.getTime();
    }
}
